define(['ionic'], function () {

    angular.module('MessageReminds', ['ionic'])

    /******路由配置******/
        .config(['$stateProvider', '$urlRouterProvider', '$ionicConfigProvider', function ($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
            $stateProvider
                .state('messages', {
                    url: '/messages',
                    templateUrl: 'tpls/messages.html',
                    controller: 'MessagesCtrl'
                })
                .state('message', {
                    url: '/messages/:msgType',
                    templateUrl: 'tpls/message.html',
                    controller: 'MessageCtrl'
                })
                .state('message-details', {
                    url: '/messages/:msgType/:msgId',
                    templateUrl: 'tpls/details.html',
                    controller: 'DetailsCtrl',
                    resolve: {
                        'ensureUnReadMessageLoaded': ['$q', '$stateParams', 'MessageService',
                            function ($q, $stateParams, MessageService) {
                                var defer = $q.defer();

                                MessageService.getUnReadMessage($stateParams.msgType).finally(function () {
                                    defer.resolve(true);
                                });

                                return defer.promise;
                            }
                        ]
                    }
                });
            $urlRouterProvider.otherwise('/messages');

            $ionicConfigProvider.platform.android.navBar.alignTitle('center');
            $ionicConfigProvider.platform.android.backButton.previousTitleText(false);
            $ionicConfigProvider.platform.android.navBar.transition('view');
            $ionicConfigProvider.platform.android.views.transition('ios');
            $ionicConfigProvider.platform.android.views.swipeBackEnabled(true);
            $ionicConfigProvider.platform.android.views.swipeBackHitWidth(45);
            $ionicConfigProvider.platform.android.tabs.style('standard');
            $ionicConfigProvider.platform.android.tabs.position('bottom');
            $ionicConfigProvider.platform.android.form.toggle('large');

            $ionicConfigProvider.platform.default.backButton.previousTitleText(false);
            $ionicConfigProvider.platform.default.backButton.text(false);
        }])

    /******服务******/
        .constant('MSGCONSTANTS', {
            GetUnReadMessageCmd: 'UFIDA.U9.ISV.MessageRemindSV.IGetUnReadMessageSV',
            GetAllReadMessageNumCmd: 'UFIDA.U9.ISV.MessageRemindSV.IGetAllUnReadMessageCountSV',
            markMessageToReadCmd: 'UFIDA.U9.ISV.MessageRemindSV.IUpdateSingleMessageToReadedSV',
            CSMessage: '个人消息',
            WorkFlowMessage: '审批任务',
            SystemMessage: '系统消息',
            CSTaskRemind: '个人任务',
            CSCalendarRemind: '个人日历',
            DocMsg: '单据留言',
            ConferenceMsg: '会议消息',
            boardMsg: '公告消息',
            CoopTaskMsg: '协同事项',
            FDocMessageNav: '公文消息'
        })

        .factory('MessageService', ['$q', '$filter', 'MSGCONSTANTS', function ($q, $filter, MSGCONSTANTS) {
            var o = {},
                unReadMessageNum = {},
                messageCache = {};

            o.loadAllUnReadMessageNum = function () {
                var defer = $q.defer();

                u9.callSV({
                    name: MSGCONSTANTS.GetAllReadMessageNumCmd,
                    params: [],
                    onSuccess: function (data) {
                        angular.forEach(data, function (unReadMessage) {
                            unReadMessageNum[unReadMessage.MessageTypeCode] = unReadMessage.UnReadCount;
                        });
                        defer.resolve(unReadMessageNum);
                    },
                    onFailure: function (err) {
                        defer.reject(err);
                    }
                });

                return defer.promise;
            };

            o.getUnReadMessage = function (messageType) {
                var defer = $q.defer();

                if (unReadMessageNum[messageType] <= 0) {
                    defer.resolve([]);
                } else if (messageCache[messageType]) {
                    defer.resolve(messageCache[messageType]);
                } else {
                    u9.showLoading();
                    u9.callSV({
                        name: MSGCONSTANTS.GetUnReadMessageCmd,
                        params: [false, messageType],
                        onSuccess: function (data) {
                            messageCache[messageType] = $filter('orderBy')(data, 'SendTime', true);;
                            defer.resolve(messageCache[messageType]);
                            u9.hideLoading();
                        },
                        onFailure: function (err) {
                            defer.reject(err);
                            u9.hideLoading();
                        }
                    });
                }

                return defer.promise;
            };

            o.markMessageToRead = function (msgType, msgId) {
                var defer = $q.defer();

                u9.callSV({
                    name: MSGCONSTANTS.markMessageToReadCmd,
                    params: [true, msgId],
                    onSuccess: function (data) {
                        deleteReadMsg(msgType, msgId);
                        unReadMessageNum[msgType]--;
                        defer.resolve(data);
                    },
                    onFailure: function (err) {
                        defer.reject(err);
                    }
                });

                return defer.promise;
            };

            o.getAllUnReadMessageNum = function () {
                return unReadMessageNum;
            };

            o.getMsgProfile = function (msgType) {
                var msgProfile = [];
                angular.forEach(messageCache[msgType], function (activeMsg) {
                    msgProfile.push({
                        ID: activeMsg.ID,
                        Title: activeMsg.Title,
                        SenderName: activeMsg.SenderName,
                        SendTime: activeMsg.SendTime
                    });
                });
                return msgProfile;
            };

            o.getMsgDetails = function (msgType, msgId) {
                var msgDetails = {},
                    activeMsgs = messageCache[msgType],
                    len = activeMsgs.length,
                    msg;
                for(var i = 0; i < len; i++) {
                    if (activeMsgs[i].ID.toString() === msgId) {
                        msg = activeMsgs[i];
                        break;
                    }
                }
                if (!msg) {
                    return msgDetails;
                }
                msgDetails.SenderName = msg.SenderName;
                msgDetails.SendTime = msg.SendTime;
                msgDetails.Title = msg.Title;
                msgDetails.Content = msg.Content;

                return msgDetails;
            };

            return o;

            function deleteReadMsg (msgType, msgId) {
                var activeMsgs = messageCache[msgType],
                    len = activeMsgs.length,
                    msg;
                for(var i = 0; i < len; i++) {
                    if (activeMsgs[i].ID.toString() === msgId) {
                        activeMsgs.splice(i, 1);
                        break;
                    }
                }
            }
        }])

    /******控制器******/
        .controller('MessagesCtrl', ['$scope', 'MessageService', 'MSGCONSTANTS',
            function ($scope, MessageService, MSGCONSTANTS) {
                $scope.headerUnReadMessages = [{
                    name: MSGCONSTANTS.CSMessage,
                    msgType: 'CSMessage',
                    msgNum: '',
                    img: 'MyMessage.png'
                }, {
                    name: MSGCONSTANTS.WorkFlowMessage,
                    msgType: 'WorkFlowMessage',
                    msgNum: '',
                    img: 'ApprovalTask.png'
                }, {
                    name: MSGCONSTANTS.SystemMessage,
                    msgType: 'SystemMessage',
                    msgNum: '',
                    img: 'SystemMessage.png'
                }];
                $scope.contentUnReadMessages = [{
                    name: MSGCONSTANTS.CSTaskRemind,
                    msgType: 'CSTaskRemind',
                    msgNum: ''
                }, {
                    name: MSGCONSTANTS.CSCalendarRemind,
                    msgType: 'CSCalendarRemind',
                    msgNum: ''
                }, {
                    name: MSGCONSTANTS.DocMsg,
                    msgType: 'DocMsg',
                    msgNum: ''
                }, {
                    name: MSGCONSTANTS.ConferenceMsg,
                    msgType: 'ConferenceMsg',
                    msgNum: ''
                }, {
                    name: MSGCONSTANTS.boardMsg,
                    msgType: 'boardMsg',
                    msgNum: ''
                }, {
                    name: MSGCONSTANTS.CoopTaskMsg,
                    msgType: 'CoopTaskMsg',
                    msgNum: ''
                }, {
                    name: MSGCONSTANTS.FDocMessageNav,
                    msgType: 'FDocMessageNav',
                    msgNum: ''
                }];

                init();

                $scope.$on('$ionicView.afterEnter', update);

                function init () {
                    u9.showLoading();
                    MessageService.loadAllUnReadMessageNum().then(function () {
                        update();
                    }, function () {
                        u9.alert('加载数据失败');
                    }).finally(function () {
                        u9.hideLoading();
                    });
                }

                function update () {
                    var unReadMessages = MessageService.getAllUnReadMessageNum();
                    angular.forEach($scope.headerUnReadMessages, function (headerUnReadMessage) {
                        var msgCount = unReadMessages[headerUnReadMessage.msgType];
                        headerUnReadMessage.msgNum = msgCount <= 0 ? '' : msgCount;
                    });
                    angular.forEach($scope.contentUnReadMessages, function (contentUnReadMessage) {
                        var msgCount = unReadMessages[contentUnReadMessage.msgType];
                        contentUnReadMessage.msgNum = msgCount <= 0 ? '' : msgCount;
                    });
                }
            }
        ])

        .controller('MessageCtrl', ['$scope', '$stateParams', 'MessageService', 'MSGCONSTANTS',
            function ($scope, $stateParams, MessageService, MSGCONSTANTS) {
                $scope.msgType = $stateParams.msgType;

                $scope.messageData = [];
                $scope.numberOfItemsToDisplay = 10;
                $scope.noMoreItemsAvailable = false;

                $scope.loadMore = function () {
                    if ($scope.messageData && $scope.messageData.length != 0) {
                        if ($scope.messageData.length > $scope.numberOfItemsToDisplay) {
                            $scope.numberOfItemsToDisplay += 10;
                        } else {
                            $scope.noMoreItemsAvailable = true;
                        }
                    } else {
                        $scope.noMoreItemsAvailable = true;
                    }
                    $scope.$broadcast('scroll.infiniteScrollComplete');
                };

                $scope.$on('$ionicView.afterEnter', function () {
                    updateTitle();
                    init();
                });

                function init () {
                    MessageService.getUnReadMessage($stateParams.msgType).then(function () {
                        $scope.messageData = MessageService.getMsgProfile($stateParams.msgType);
                        $scope.noMoreItemsAvailable = false;
                    }, function () {
                        u9.alert('加载数据失败');
                    });
                }

                function updateTitle () {
                    var unReadMessages = MessageService.getAllUnReadMessageNum(),
                        msgCount = unReadMessages[$stateParams.msgType];
                    if (msgCount <= 0) {
                        $scope.title = MSGCONSTANTS[$stateParams.msgType]
                    } else {
                        $scope.title = MSGCONSTANTS[$stateParams.msgType] + '(' + msgCount + ')';
                    }
                }
            }
        ])

        .controller('DetailsCtrl', ['$scope', '$stateParams', '$ionicHistory', 'MessageService', 'MSGCONSTANTS',
            function ($scope, $stateParams, $ionicHistory, MessageService, MSGCONSTANTS) {
                $scope.msgType = $stateParams.msgType;
                $scope.msgId = $stateParams.msgId;

                $scope.name = MSGCONSTANTS[$stateParams.msgType];
                $scope.msgDetails = MessageService.getMsgDetails($stateParams.msgType, $stateParams.msgId);

                $scope.markMsgToRead = function () {
                    MessageService.markMessageToRead($stateParams.msgType, $scope.msgId).then(function (data) {
                        $ionicHistory.goBack();
                    }, function () {
                        u9.alert('标记已读失败');
                    });
                };
            }
        ]);
});